import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import moment from 'moment';
import { Button, Card, DatePicker, Icon, message, Radio, Table } from 'antd';

import TreeMultiSelect from '@/components/TreeMultiSelect';
import EchartsLine from '@/components/Dashboard/EchartsLine';
import { DATE_TIME_FORMAT } from '@/utils/constants';
import { PageLoading } from '@ant-design/pro-layout';

const { RangePicker } = DatePicker;

class HistoryCard extends Component {

  constructor(props) {
    super(props);
    // const treeData = this.buildTreeData(props.searchParams);
    this.state = {
      showType: 'line',
      treeData: this.buildTreeData(props.searchParams),
      treeSelectValue: [],
      startTimeValue: moment().subtract(1, 'day').format(DATE_TIME_FORMAT),
      endTimeValue: moment().format(DATE_TIME_FORMAT),
    };
  }

  searchData = () => {
    const { treeSelectValue, startTimeValue, endTimeValue, showType } = this.state;
    if (!treeSelectValue || treeSelectValue.length === 0) {
      message.warning('请选择历史查询参数');
    } else {
      const h = (typeof treeSelectValue) === 'string' ? treeSelectValue : treeSelectValue.join('|||');
      const payload = { h, pageNo: showType === 'line' ? -1 : 1, startTime: startTimeValue, endTime: endTimeValue };
      payload.pageNo = -1;
      this.props.dispatch({ type: 'historyData/fetch', payload });
    }
  };

  // handlePageChange = (changePageNo) => {
  //   const { pageNo, dispatch } = this.props;
  //   if (changePageNo !== pageNo) {
  //     dispatch({ type: 'historyData/fetch', payload: { pageNo: changePageNo } });
  //   }
  // };

  buildTreeData = (searchParams, parentNode = null) => {
    const treeData = [];
    if (searchParams && searchParams.length > 0) {
      for (let i = 0; i < searchParams.length; i++) {
        if (searchParams[i].children) {
          searchParams[i].selectable = false;
          const node = {
            title: searchParams[i].title,
            key: searchParams[i].key,
            parent: parentNode,
          };
          node.children = this.buildTreeData(searchParams[i].children, node);
          treeData.push(node);
        } else {
          treeData.push({
            title: searchParams[i].title,
            value: searchParams[i].title + '||' + searchParams[i].historyOrds.join('|||'),
            key: searchParams[i].key,
            parent: parentNode,
          });
        }
      }
    }
    return treeData;
  };


  // componentDidMount() {
  //   this.searchData();
  // }

  componentWillReceiveProps(nextProps) {
    if (nextProps.searchParams !== this.props.searchParams) {
      this.setState({
        showType: 'line',
        treeData: this.buildTreeData(nextProps.searchParams),
        treeSelectValue: [],
      });
    }
    if (nextProps.names !== this.props.names || nextProps.lists !== this.props.lists) {
      const { names, lists } = nextProps;
      const { xDatas, yDatas } = this.createEchartsData(lists);
      if ((this.state.showType === 'line' || this.state.showType === 'bar') && this.echartsLine) {
        this.echartsLine.updateChart(names, yDatas, this.state.showType, xDatas);
      }
    }
  }

  createEchartsData = (lists = [], names=[]) => {
    let xDatas = [], yDatasN = [], tDatas = [];
    lists.forEach((list) => {
      const yData = {};
      list.forEach((data) => {
        xDatas.push(data.time);
        yData[data.time] = [data.time, data.value];
      });
      yDatasN.push(yData);
    });
    xDatas = [...new Set(xDatas)];
    xDatas.sort((a, b) => (new Date(a) - new Date(b)));
    const yDatas = [];
    yDatasN.forEach((list)=>{
      const yData = [];
      xDatas.forEach((xData)=>{
        if(list[xData]) {
          yData.push(list[xData]);
        }
      });
      yDatas.push(yData);
    });
    if(names && names.length > 0) {
      const newLists = [];
      lists.forEach((list) => {
        const newList = Array(xDatas.length).fill('-');
        list.forEach((data) => {
          const idx = xDatas.indexOf(data.time);
          newList[idx] = data.value;
        });
        newLists.push(newList);
      });
      xDatas.forEach((xData, idx)=>{
        const tData = {id: (idx+1), time: xData};
        names.forEach((name, index)=>{
          tData[name] = newLists[index][idx];
        })
        tDatas.push(tData);
      });
    }
    return { xDatas, yDatas, tDatas };
  };

  dateChange = (values) => {
    const startTimeValue = values[0].format(DATE_TIME_FORMAT);
    const endTimeValue = values[1].format(DATE_TIME_FORMAT);
    this.setState({ startTimeValue, endTimeValue });
  };

  render() {
    const { names, lists, loading } = this.props;
    if(loading) {
      return <PageLoading/>;
    }
    const { showType, treeData, treeSelectValue, startTimeValue, endTimeValue } = this.state;
    const title = (
      <Radio.Group value={showType}
                   buttonStyle='solid'
                   onChange={event => this.setState({ showType: event.target.value })}>
        <Radio.Button value='line'><Icon type='line-chart'/></Radio.Button>
        <Radio.Button value='table'><Icon type='table'/></Radio.Button>
        <Radio.Button value='bar'><Icon type='bar-chart'/></Radio.Button>
      </Radio.Group>
    );
    const extra = (
      <span className={'space8'}>
        <TreeMultiSelect
          style={{ width: 300 }}
          value={treeSelectValue}
          treeData={treeData}
          onChange={treeSelectValue => this.setState({ treeSelectValue })}
          placeholder='选择查询参数'
          multiple={true}
        />
        <RangePicker
          showTime={{ format: 'HH:mm:ss' }}
          format={DATE_TIME_FORMAT}
          value={[moment(startTimeValue, DATE_TIME_FORMAT), moment(endTimeValue, DATE_TIME_FORMAT)]}
          placeholder={['开始时间', '结束时间']}
          onChange={this.dateChange}
        />
        <Button type='primary' onClick={() => this.searchData()}>
          <Icon type={'search'}/>查询
        </Button>
      </span>
    );
    let dom = <></>;
    const { xDatas, yDatas, tDatas } = this.createEchartsData(lists, names);
    if (showType === 'table') {
      const columns = [{
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
      }, {
        title: '采集时间',
        dataIndex: 'time',
        key: 'time',
      }];
      names.forEach((column) => {
        columns.push({
          title: column,
          dataIndex: column,
          key: column,
        });
      });
      dom = (<Table
        className={'common-table-wrapper'}
        columns={columns}
        dataSource={tDatas}
        rowKey='_id'
        loading={loading}
        pagination={{
          total: tDatas.length,
          pageSize: tDatas.length,
          current: 1
        }}
        scroll={{ y: 500 }}
      />);
    } else {
      dom = (
        <EchartsLine ref={(e) => {
          this.echartsLine = e;
        }} title='查询结果' legends={names} xDatas={xDatas} datas={yDatas} showType={showType} bDashboard={false}/>
      );
    }
    return (
      <Card title={title} extra={extra} style={{ height: '100%' }} bodyStyle={{ height: '80%' }}>
        {dom}
      </Card>
    );
  }
}

HistoryCard.propTypes = {
  searchParams: PropTypes.array.isRequired,
};

export default connect(({ historyData, loading }) => ({
  ...historyData,
  loading: loading.effects['historyData/fetch'],
}))(HistoryCard);
